var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var _limitMenu = system.MENULIMIT.REPORT10;
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH + 'report/sell_compare';
var Utils = {
    initYear:function(){
		var d = new Date();
		var arr = [];
		arr.push({"code":"无"});
		for(var i=0;i>-5;i--){
			arr.push({"code":(d.getFullYear()+i)})
		}
		yearCombo = $('#span_year').combo({
			data:arr,
			value: 'code',
			text: 'code',
			width : 207,
			height: 80,
			listId:'',
			defaultSelected: 0,
			editable: true,
			callback:{
				onChange: function(data){
					$("#pd_year").val(data.code);
				}
			}
		}).getCombo();
	},
	initSeason:function(){
		seasonCombo = $('#span_season').combo({
			value: 'dtl_code',
			text: 'dtl_name',
			width :206,
			height: 80,
			listId:'',
			defaultSelected: 0,
			editable: true,
			callback:{
				onChange: function(data){
					if(data.dtl_name == "全部"){
						$("#pd_season").val("");
					}else{
						$("#pd_season").val(data.dtl_name);
					}
				}
			}
		}).getCombo(); 
		$.ajax({
			type:"POST",
			url:config.BASEPATH +"base/dict/listByProduct",
			data:"",
			cache:false,
			dataType:"json",
			success:function(data){
				seasonInfo = data.data.seasonitemsquery;
				seasonCombo.loadData(seasonInfo);
			}
		});
	},
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/to_list_sub_dialog',
			data : {multiselect:false},
			width : 450,
			height : 370,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#shl_shop_code").val(selected.sp_code);
				$("#shop_name").val(selected.sp_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#shl_shop_code").val(selected.sp_code);
					$("#shop_name").val(selected.sp_name);
				}
			},
			cancel:true
		});
	},
	doQueryType : function(){
		commonDia = $.dialog({
			title : '选择商品类别',
			content : 'url:'+config.BASEPATH+'base/type/to_tree_dialog',
			data : {multiselect:true},
			width : 280,
		   	height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var pd_tp_code = [];
				var pd_tp_name = [];
				for(var i=0;i<selected.length;i++){
					pd_tp_code.push(selected[i].tp_code);
					pd_tp_name.push(selected[i].tp_name);
				}
				$("#tp_code").val(pd_tp_code.join(","));
				$("#tp_name").val(pd_tp_name.join(","));
			},
			close:function(){
				if(commonDia.content.dblClick){
					var selected = commonDia.content.doSelect();
					var pd_tp_code = [];
					var pd_tp_name = [];
					for(var i=0;i<selected.length;i++){
						pd_tp_code.push(selected[i].tp_code);
						pd_tp_name.push(selected[i].tp_name);
					}
					$("#tp_code").val(pd_tp_code.join(","));
					$("#tp_name").val(pd_tp_name.join(","));
					}
				},
				cancel:true
			});
		},
	doQueryBrand : function(){
		commonDia = $.dialog({
			title : '选择品牌',
		content : 'url:'+config.BASEPATH+'base/brand/to_list_dialog',
		data : {multiselect:true},
		width : 320,
		height : 370,
		max : false,
		min : false,
		cache : false,
		lock: true,
		ok:function(){
			var selected = commonDia.content.doSelect();
			if (!selected) {
				return false;
			}
			var pd_bd_code = [];
			var pd_bd_name = [];
			for(var i=0;i<selected.length;i++){
				pd_bd_code.push(selected[i].bd_code);
				pd_bd_name.push(selected[i].bd_name);
			}
			$("#bd_code").val(pd_bd_code.join(","));
			$("#bd_name").val(pd_bd_name.join(","));
		},
		close:function(){
			if(commonDia.content.dblClick){
				var selected = commonDia.content.doSelect();
				var pd_bd_code = [];
				var pd_bd_name = [];
				for(var i=0;i<selected.length;i++){
					pd_bd_code.push(selected[i].bd_code);
					pd_bd_name.push(selected[i].bd_name);
				}
				$("#bd_code").val(pd_bd_code.join(","));
				$("#bd_name").val(pd_bd_name.join(","));
				}
			},
			cancel:true
		});
    }, 
    exportExcel: function () {
        window.location.replace(cinfig.BASEPATH + "report/sell_compare_export?" + THISPAGE.initParam() + "&print=1");
    }
}

var queryConditions = {

};

var THISPAGE = {
    init: function () {
        this.initDom();
        this.initGrid();
        this.initEvent();
        Utils.initSeason();
        Utils.initYear();
    },
    initDom: function () {
        this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
		dateRedioClick("theDate");

    },
    initType:function(type){
		$("#tab_type").children("a").each(function(){
			$(this).removeClass("on");
		});
		$("#btn_"+type).addClass("on")
		$("#type").val(type);
		$("#grid").clearGridData(false);
	},
    initRow:function(){
		var ids = $("#grid").getDataIDs();
        for (var i = 0; i < ids.length; i++) {
            var before = $("#grid").jqGrid('getRowData', ids[i]);
            var index = 1;
            for (var j = i + 1; j <= ids.length; j++) {
            	if(undefined != ids[j]){
	                var end = $("#grid").jqGrid('getRowData', ids[j]);
	                if (before['bd_name'] == end['bd_name']) {
	                	index++;
	                    $("#grid").setCell(ids[j], 'bd_name', '', { display: 'none' });
	                } else {
	                	index = 1;
	                	break;
	                }
	                if(index > 1){
	                	$("#bd_name_" + ids[i]).prop("rowspan", index);
	                }
            	}
            }
        }
	},
    initGrid: function () {
        var gridWH = Public.setGrid();
        var colModel = [
            {label: "编号", name: 'bd_code', index: 'bd_code', hidden:true, title: false,sortable:false},
            {label: "名称", name: 'bd_name', index: 'bd_name', width: 90, align: 'left', title: false,sortable:false,
            	cellattr: function(rowId, tv, rawObject, cm, rdata) {return 'id="bd_name_' + rowId + '"';}	
            },
            {label: '项目',name: 'shl_type', index: 'shl_type', width:50, align: 'center', sortable:false,title: false,sortable:false}
        ];
        for (var i = 1; i <= 12; i++) {
        	colModel.push({label:'数量',name: "shl_amount"+i,index:'',width: 45, title: true,sortable:false,align:'right',sorttype:'int'});
			colModel.push({label:'金额',name: "shl_money"+i,index:'',width: 58, title: true,sortable:false,align:'right',sorttype:'float'});
			colModel.push({label:'毛利',name: "shl_profit"+i,index:'',width: 58, title: true,sortable:false,align:'right',sorttype:'float'});
		}
        $('#grid').jqGrid({
            loadonce: true, 
            datatype: 'local',
            width: gridWH.w-12,
			height: gridWH.h-20,
            gridview: true,
            onselectrow: false,
            colModel: colModel,
            rownumbers: true,//行号
            pgbuttons:true,
            recordtext: '{0} - {1} 共 {2} 条',
            rowNum: -1,//每页条数
            shrinkToFit: false,//表格是否自动填充
            jsonReader: {
            	root: 'data',
                repeatitems: false,
                id: 'shl_id'
            },
            loadComplete: function (data) {
            	THISPAGE.initRow();
//            	THISPAGE.buildTotal();
            },
            loadError: function (xhr, status, error) {
                Public.tips({type: 1, content: '连接超时，请刷新！'});
            }
        });
        var header = [];
        for (var i=1 ;i <= 12; i++){ 
        	header.push({startColumnName : 'shl_amount'+i,numberOfColumns : 3, titleText : i+"月"});
        }
        header.push({startColumnName : 'Totalamount',numberOfColumns : 3, titleText :'小计' });
        $("#grid").jqGrid('setGroupHeaders', { 
			useColSpanStyle : true,
			groupHeaders : header
		});
    },
    buildTotal:function(){
    	var grid = $("#grid"),json = {};
    	for (var i=1 ;i <= 12; i++){ 
	    	var shl_amount = grid.getCol('shl_amount'+i,false,'sum');
	    	var shl_money = grid.getCol('shl_money'+i,false,'sum');
	    	var shl_profit = grid.getCol('shl_profit'+i,false,'sum');
	    	json["shl_amount"+i] = shl_amount;
	    	json["shl_money"+i] = shl_money;
	    	json["shl_profit"+i] = shl_profit;
    	}
    	grid.footerData('set',json);
    },
    initParam:function(){
    	var type = $("#type").val();
    	var params = '';
		params += 'begindate='+$("#begindate").val();
		params += '&enddate='+$("#enddate").val();
		params += '&bd_code='+$("#bd_code").val();
		params += '&tp_code='+$("#tp_code").val();
		params += '&type='+type;
		params += '&shl_shop_code='+$("#shl_shop_code").val();
		return params;
    },
    reloadData: function (data) {
        $("#grid").jqGrid('setGridParam', {datatype: 'json', page: 1, url: queryurl + "?" + THISPAGE.initParam()}).trigger("reloadGrid");
    },
    reset:function(){
		$("#shop_name").val("");
		$("#shl_shop_code").val("");
		$("#bd_code").val("");
		$("#tp_code").val("");
		$("#type").val("brand");
		yearCombo.selectByIndex(0);
		seasonCombo.selectByIndex(0);
		THISPAGE.$_date.setValue(0);
	},
    initEvent: function () {
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		$("#btn_brand").on('click',function(){
			THISPAGE.initType("brand");
		});
		$("#btn_type").on('click',function(){
			THISPAGE.initType("type");
		});
		$("#btn_emp").on('click',function(){
			THISPAGE.initType("emp");
		});
		$("#btn_shop").on('click',function(){
			THISPAGE.initType("shop");
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
    }
}
THISPAGE.init();